package com.eqdd.yiqidian.ui.gongneng.daka;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.databinding.DataBindingUtil;
import android.graphics.drawable.Icon;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.Toast;

import com.eqdd.yiqidian.DakaActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.DakaBean;
import com.eqdd.yiqidian.bean.rebuild.ClockBean;
import com.eqdd.yiqidian.bean.rebuild.RuleResultBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.receiver.MyReceive;
import com.eqdd.yiqidian.ui.LoginActivity;
import com.eqdd.yiqidian.ui.SplashActivity;
import com.eqdd.yiqidian.utils.DakaUtil;
import com.eqdd.yiqidian.utils.DateUtil;
import com.eqdd.yiqidian.utils.LauncherUtil;
import com.eqdd.yiqidian.utils.SPUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.jakewharton.rxbinding.view.RxView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.orhanobut.logger.Logger;
import com.xys.shortcut_lib.ShortcutUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.functions.BiFunction;
import io.rong.imkit.plugin.location.AMapLocationInfo;
import io.rong.imkit.plugin.location.IMyLocationChangedListener;
import io.rong.imkit.plugin.location.LocationManager;
import io.rong.imlib.model.Conversation;
import rx.Subscriber;
import rx.Subscription;
import shortbread.Shortcut;
import zwh.com.lib.FPerException;
import zwh.com.lib.RxFingerPrinter;

//@Shortcut(id = "daka", icon = R.mipmap.kehu, shortLabel = "打卡")
public class DakaActivity extends BaseActivity implements IMyLocationChangedListener {
    private DakaActivityCustom dataBinding;
    private boolean isSingle;
    String[] weeks = new String[]{
            "日",
            "一",
            "二",
            "三",
            "四",
            "五",
            "六"
    };
    private SlimAdapterEx<DakaBean> slimAdapterEx;
    private SlimAdapterEx slimAdapterExDaka;
    private List<ClockBean> historyClockList;
    private RuleResultBean ruleList;
    private ArrayList<DakaItemBean> dakaItemBeans;
    private SimpleDateFormat sfDaka;
    private String location;
    private String coordinate;
    SparseArray<String> statusMap = new SparseArray();
    private RxFingerPrinter rxFingerPrinter;
    private Subscription subscription;

//    @Shortcut(id = "daka", icon = R.mipmap.add, shortLabel = "Add movie")
//    public void addMovie() {
//        // code to add movie, could show an AddMovieDialogFragment for example
//        System.out.println("addmovie");
//    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_daka);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月");
        initTopTitleBar(View.VISIBLE, sf.format(new Date()));
        initTopRightText("打卡记录", v -> {
            startActivity(DakaListActivity.class);
        });
        statusMap.put(0, "正常");
        statusMap.put(1, "迟到");
        statusMap.put(2, "早退");
        statusMap.put(-1, "打卡");
        statusMap.put(-2, "漏打卡");
        statusMap.put(-3, "未开始");
//        if (LauncherUtil.isShortCutExist(this, "打卡")) {
//            Toast.makeText(this, "添加桌面快捷方式成功", Toast.LENGTH_SHORT).show();
//        } else {
//            Toast.makeText(this, "创建桌面图标失败，请检查系统应用设置快捷方式权限", Toast.LENGTH_LONG).show();
//        }
//        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            addShortCut(this);
//        } else {
//            // 设置关联程序
//            Intent sIntent = new Intent(Intent.ACTION_MAIN);
//            sIntent.putExtra("duplicate", false);
//            sIntent.addCategory(Intent.CATEGORY_LAUNCHER);// 加入action,和category之后，程序卸载的时候才会主动将该快捷方式也卸载
//            sIntent.setClass(this, DakaActivity.class);//点击后进入的Activity
//            // 发送广播
//            ShortcutUtils.addShortcut(this, sIntent, "打卡", false, R.mipmap.add);
//
//        }
        if (user == null) {
            if (SPUtil.getFirst(AppConstent.first_open_app)) {
                Logger.d("进入闪屏页");
                System.out.println("进入闪屏页");

                startActivity(SplashActivity.class);
            } else {
                Logger.d("进入登录页");
                System.out.println("进入登录页");

                startActivity(LoginActivity.class);
            }
            finish();
            return;
        }
        System.out.println(user);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void addShortCut(Context context) {
        ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE);
        if (shortcutManager.isRequestPinShortcutSupported()) {
            Intent shortcutInfoIntent = new Intent(context, DakaActivity.class);
            shortcutInfoIntent.setAction(Intent.ACTION_VIEW); //action必须设置，不然报错

            ShortcutInfo info = new ShortcutInfo.Builder(context, "1024")
                    .setIcon(Icon.createWithResource(context, R.mipmap.add))
                    .setShortLabel("打卡")
                    .setIntent(shortcutInfoIntent)
                    .build();

            //当添加快捷方式的确认弹框弹出来时，将被回调
            PendingIntent shortcutCallbackIntent = PendingIntent.getBroadcast(context, 0,
                    new Intent(context, MyReceive.class), PendingIntent.FLAG_UPDATE_CURRENT);

            shortcutManager.requestPinShortcut(info, shortcutCallbackIntent.getIntentSender());
        }

    }


    protected String dealText(String text) {
        return TextUtils.isEmpty(text) ? " " : text;
    }

    @Override
    public void initData() {
        if (user != null) {
            LocationManager.getInstance().bindConversation(this, Conversation.ConversationType.PRIVATE, user.getGuid());
            LocationManager.getInstance().setMyLocationChangedListener(this);
            LocationManager.getInstance().updateMyLocation();
            // where this is an Activity instance
            rxFingerPrinter = new RxFingerPrinter(this);
            subscription = rxFingerPrinter
                    .begin()
                    .subscribe(new Subscriber<Boolean>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            if (e instanceof FPerException) {
//                                        ToastUtil.showShort(((FPerException) e).getDisplayMessage());
                            }
                        }

                        @Override
                        public void onNext(Boolean aBoolean) {
                            if (aBoolean) {

//                                        Flowable.fromIterable(slimAdapterEx.get)
                            } else {
                                ToastUtil.showShort("指纹识别失败");
                            }
                        }
                    });
            rxFingerPrinter.addSubscription(this, subscription); //不要忘记把订阅返回的subscription添加到rxfingerPrinter里
        }
        sfDaka = new SimpleDateFormat("yyyy/M/d");
        dakaItemBeans = new ArrayList<>();
        dataBinding.recyclerViewDaka.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterExDaka = SlimAdapterEx.create().register(R.layout.list_item_50, new SlimInjector<DakaItemBean>() {
            @Override
            public void onInject(DakaItemBean data, IViewInjector injector) {

                injector
                        .text(R.id.tv_upper_left_content, "上班打卡")
                        .text(R.id.tv_upper_left_content_first, "下班打卡")
                        .text(R.id.tv_down_left_content, data.ruleStartTime)
                        .text(R.id.tv_down_left_content_first, data.ruleEndTime)
                        .text(R.id.tv_3_first, "重打")
                        .text(R.id.tv_2_first, statusMap.get(data.endStatus))
                        .text(R.id.tv_1_first, "打卡" + data.endDakaTime)
                        .text(R.id.tv_2, statusMap.get(data.startStatus))
                        .text(R.id.tv_1, "打卡" + data.startDakaTime)
                        .text(R.id.bt_down_right, statusMap.get(data.endStatus))
                        .text(R.id.bt_upper_right, statusMap.get(data.startStatus))
                        .enable(R.id.bt_upper_right, data.startStatus == -1)
                        .enable(R.id.bt_down_right, data.endStatus == -1)
                        .visibility(R.id.rl_upper_right, data.startStatus < 0 ? View.GONE : View.VISIBLE)
                        .visibility(R.id.bt_upper_right, data.startStatus >= 0 ? View.GONE : View.VISIBLE)
                        .visibility(R.id.rl_down_right, data.endStatus < 0 ? View.GONE : View.VISIBLE)
                        .visibility(R.id.bt_down_right, data.endStatus >= 0 ? View.GONE : View.VISIBLE)
                        .clicked(R.id.tv_3_first, v -> {
                            playMic();
                            OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.UPDATE_CLOCK)
                                    .params("userGuid", user.getGuid())
                                    .params("companyId", user.getCompanyId())
                                    .params("clockTime", data.ruleEndTime)
                                    .params("place", dealText(location))
                                    .params("MAC", DakaUtil.getPhoneMac(DakaActivity.this))
                                    .params("WIFIName", DakaUtil.getWiFiName(DakaActivity.this))
                                    .params("phoneUUID", DakaUtil.getPhoneUUID(DakaActivity.this))
                                    .params("phoneType", android.os.Build.MODEL)
                                    .params("coordinate", dealText(coordinate))
                                    .params("clockId", data.endId)
                                    .params("type", 1)
                                    .execute(new DialogCallBack<HttpResult>(DakaActivity.this) {
                                        @Override
                                        public void onSuccess(Response<HttpResult> response) {
                                            HttpResult httpResult = response.body();
                                            ToastUtil.showShort(httpResult.getMsg());
                                            if (httpResult.getStatus() == 200) {
                                                Date date = DateUtil.parseNetTime(response.getRawResponse().header("Date"));
                                                SimpleDateFormat sf = new SimpleDateFormat("HH:mm");
                                                data.endDakaTime = sf.format(date);
                                                if (data.endDakaTime.compareTo(data.ruleEndTime) >= 0) {
                                                    data.endStatus = 0;
                                                } else {
                                                    data.endStatus = 2;
                                                }
                                                slimAdapterExDaka.notifyItemChanged(slimAdapterExDaka.getData().indexOf(data));
                                            }
                                        }
                                    });
                        })
                        .clicked(R.id.bt_upper_right, v -> {
                            playMic();
                            OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.CREATE_CLOCK)
                                    .params("userGuid", user.getGuid())
                                    .params("companyId", user.getCompanyId())
                                    .params("clockTime", data.ruleStartTime)
                                    .params("place", dealText(location))
                                    .params("MAC", DakaUtil.getPhoneMac(DakaActivity.this))
                                    .params("WIFIName", DakaUtil.getWiFiName(DakaActivity.this))
                                    .params("phoneUUID", DakaUtil.getPhoneUUID(DakaActivity.this))
                                    .params("phoneType", android.os.Build.MODEL)
                                    .params("coordinate", dealText(coordinate))
                                    .params("type", 0)
                                    .execute(new DialogCallBack<HttpResult>(DakaActivity.this) {
                                        @Override
                                        public void onSuccess(Response<HttpResult> response) {
                                            HttpResult httpResult = response.body();
                                            ToastUtil.showShort(httpResult.getMsg());
                                            if (httpResult.getStatus() == 200) {
                                                Date date = DateUtil.parseNetTime(response.getRawResponse().header("Date"));
                                                SimpleDateFormat sf = new SimpleDateFormat("HH:mm");
                                                data.startDakaTime = sf.format(date);
                                                if (data.startDakaTime.compareTo(data.ruleStartTime) > 0) {
                                                    data.startStatus = 1;
                                                } else {
                                                    data.startStatus = 0;
                                                }
                                                slimAdapterExDaka.notifyItemChanged(slimAdapterExDaka.getData().indexOf(data));

                                            }
                                        }
                                    });
                        })
                        .clicked(R.id.bt_down_right, v -> {
                            playMic();
                            OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.CREATE_CLOCK)
                                    .params("userGuid", user.getGuid())
                                    .params("companyId", user.getCompanyId())
                                    .params("clockTime", data.ruleEndTime)
                                    .params("place", dealText(location))
                                    .params("MAC", DakaUtil.getPhoneMac(DakaActivity.this))
                                    .params("WIFIName", DakaUtil.getWiFiName(DakaActivity.this))
                                    .params("phoneUUID", DakaUtil.getPhoneUUID(DakaActivity.this))
                                    .params("phoneType", android.os.Build.MODEL)
                                    .params("coordinate", dealText(coordinate))
                                    .params("type", 1)
                                    .execute(new DialogCallBack<HttpResult>(DakaActivity.this) {
                                        @Override
                                        public void onSuccess(Response<HttpResult> response) {
                                            HttpResult httpResult = response.body();
                                            ToastUtil.showShort(httpResult.getMsg());
                                            if (httpResult.getStatus() == 200) {
                                                Date date = DateUtil.parseNetTime(response.getRawResponse().header("Date"));
                                                SimpleDateFormat sf = new SimpleDateFormat("HH:mm");
                                                data.endDakaTime = sf.format(date);
                                                if (data.endDakaTime.compareTo(data.ruleEndTime) > 0) {
                                                    data.endStatus = 0;
                                                } else {
                                                    data.endStatus = 2;
                                                }
                                                slimAdapterExDaka.notifyItemChanged(slimAdapterExDaka.getData().indexOf(data));
                                            }
                                        }
                                    });
                        });
            }
        }).attachTo(dataBinding.recyclerViewDaka).updateData(new ArrayList());


    }

    private void playMic() {
        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone rt = RingtoneManager.getRingtone(getApplicationContext(), uri);
        rt.play();
    }

    @Override
    public void onMyLocationChanged(AMapLocationInfo aMapLocationInfo) {
        if (aMapLocationInfo != null) {
            coordinate = aMapLocationInfo.getLat() + "," + aMapLocationInfo.getLng();
            location = aMapLocationInfo.getProvince()
                    + aMapLocationInfo.getCity()
                    + aMapLocationInfo.getDistrict();
            System.out.println(location);
        }
    }

    @Override
    public void setView() {

        RxView.clicks(dataBinding.dakaSwitchView)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe((v) -> {
                    dataBinding.dakaSwitchView.setText(isSingle ? "上班打卡" : "下班打卡");
                    isSingle = !isSingle;

                });
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        LinearSnapHelper snapHelper = new LinearSnapHelper();
        snapHelper.attachToRecyclerView(dataBinding.recyclerView);
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_week, new SlimInjector<DakaBean>() {
            @Override
            public void onInject(DakaBean data, IViewInjector injector) {

                injector.text(R.id.tv_week, weeks[data.getCalendar().get(Calendar.DAY_OF_WEEK) - 1])
                        .text(R.id.tv_date, data.getCalendar().get(Calendar.DAY_OF_MONTH) + "")
                        .text(R.id.tv_tip, data.getType() == 0 ? "休息" : (data.getType() == 1) ? "工作" : "异常")
                        .textColor(R.id.tv_week, data.getType() == 0 ? getResources().getColor(R.color.hint_color) : (data.getType() == 1) ? getResources().getColor(R.color.black) : getResources().getColor(R.color.red))
                        .textColor(R.id.tv_date, data.getType() == 0 ? getResources().getColor(R.color.hint_color) : (data.getType() == 1) ? getResources().getColor(R.color.black) : getResources().getColor(R.color.red))
                        .textColor(R.id.tv_tip, data.getType() == 0 ? getResources().getColor(R.color.hint_color) : (data.getType() == 1) ? getResources().getColor(R.color.black) : getResources().getColor(R.color.red));
            }
        }).attachTo(dataBinding.recyclerView);
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                });

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sf.format(new Date());
        Flowable<HttpResult<List<ClockBean>>> clockHisFlow = OkGo.<HttpResult<List<ClockBean>>>post(HttpConfig.BASE_URL + HttpConfig.NOW_CLOCK)
                .params("userGuid", user.getGuid())
                .params("companyId", user.getCompanyId())
                .params("date", format)
                .converter(new JsonConverter<HttpResult<List<ClockBean>>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<>());

        Flowable<HttpResult<RuleResultBean>> ruleFlow = OkGo.<HttpResult<RuleResultBean>>post(HttpConfig.BASE_URL + HttpConfig.MY_RULE)
                .params("userGuid", user.getGuid())
                .params("companyId", user.getCompanyId())
                .converter(new JsonConverter<HttpResult<RuleResultBean>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<>());
//        showLoading();
        Flowable.combineLatest(clockHisFlow, ruleFlow, (BiFunction<HttpResult<List<ClockBean>>, HttpResult<RuleResultBean>, Object>) (listHttpResult, ruleResultBeanHttpResult) -> {
            historyClockList = listHttpResult.getItems();
            ruleList = ruleResultBeanHttpResult.getItems();
            System.out.println(sfDaka.format(new Date((Long) SPUtil.getParam(Config.NOW_TIME))));
            return 1;
        }).subscribe(o -> {
            if (historyClockList != null) {
                for (int i = 0; i < historyClockList.size(); i += 2) {
                    DakaItemBean dakaItemBean = new DakaItemBean();
                    dakaItemBean.ruleStartTime = historyClockList.get(i).getClockTime().substring(0, 5);
                    dakaItemBean.ruleEndTime = historyClockList.get(i + 1).getClockTime().substring(0, 5);
                    dakaItemBean.startDakaTime = historyClockList.get(i).getCreateTime();
                    dakaItemBean.startStatus = historyClockList.get(i).getStatus();
                    dakaItemBean.startId = historyClockList.get(i).getId();
                    dakaItemBean.endDakaTime = historyClockList.get(i + 1).getCreateTime();
                    dakaItemBean.endStatus = historyClockList.get(i + 1).getStatus();
                    dakaItemBean.endId = historyClockList.get(i + 1).getId();
                    dakaItemBeans.add(dakaItemBean);
                }
            }
            slimAdapterExDaka.updateData(dakaItemBeans);
            Calendar instance = Calendar.getInstance();
            instance.setTime(new Date());
            instance.add(Calendar.DATE, -9);
            ArrayList<DakaBean> dakaBeen = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                dakaBeen.add(new DakaBean((Calendar) instance.clone(), DateUtil.isWork((Calendar) instance.clone(), ruleList.getWeeks(), ruleList.getHolidays()) ? 1 : 0));

                instance.add(Calendar.DATE, 1);
            }
            slimAdapterEx.updateData(dakaBeen);
            dataBinding.recyclerView.smoothScrollToPosition(slimAdapterEx.getData().size() - 1);
        }, e -> ToastUtil.showLong("你还没有排班规则哦"));
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (dataBinding != null && dataBinding.dakaSwitchView != null) {
            dataBinding.dakaSwitchView.startAnim();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (rxFingerPrinter != null) {
            rxFingerPrinter.unSubscribe(this);
            rxFingerPrinter = null;
        }
        if (subscription != null) {
            if (subscription.isUnsubscribed()) {
                subscription.unsubscribe();
                subscription = null;
            }
        }
    }

    public class DakaItemBean {

        int startId;
        int endId;
        String ruleStartTime;
        String ruleEndTime;
        String startDakaTime;
        String endDakaTime;
        public int startStatus = -1;
        int endStatus = -1;

        DakaItemBean() {
        }

    }


}
